<script setup lang="ts">
/**
 * @author lwlianghehe@gmail.com
 * @date 2025/08/04
 */
import { ref, computed } from "vue";
import { ElDialog, ElButton, ElInput, ElForm, ElFormItem, ElSelect, ElOption } from 'element-plus';
import { ControlData, ControlValueItem } from './types';

const props = withDefaults(defineProps<{
  modelValue?: boolean
  title?: string
  width?: string | number
  initialData?: ControlData
}>(), {
  modelValue: false,
  title: '控件配置',
  width: '600px',
  initialData: () => ({
    type: 'text',
    placeholder: '',
    defaultValue: ''
  } as ControlData)
})

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'confirm', data: ControlData): void
  (e: 'cancel'): void
}>()

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (val: boolean) => {
    emit('update:modelValue', val)
  }
})

const formRef = ref()

// 表单数据
const formData = ref<ControlData>({
  type: 'text',
  placeholder: '',
  defaultValue: ''
})

// 值集JSON字符串
const valueSetJson = ref('')

// 表单验证规则
const rules = {
  placeholder: [
    { required: true, message: '请输入占位符', trigger: 'blur' }
  ],
  valueSet: [
    { 
      required: true, 
      message: '请输入值集', 
      trigger: 'blur',
              validator: (rule: any, value: any, callback: any) => {
          if (['enum', 'checkbox', 'radio'].includes(formData.value.type)) {
            if (!valueSetJson.value.trim()) {
              callback(new Error('请输入值集'))
            } else {
              try {
                // 清理可能的控制字符
                let cleanJson = valueSetJson.value
                  .replace(/[\u0000-\u001F\u007F-\u009F]/g, '') // 移除控制字符
                  .trim()
                
                const parsed = JSON.parse(cleanJson)
                if (!Array.isArray(parsed) || parsed.length === 0) {
                  callback(new Error('值集必须是有效的JSON数组且不能为空'))
                } else {
                  callback()
                }
              } catch (error) {
                if (error instanceof SyntaxError) {
                  callback(new Error('值集JSON格式错误，请检查是否有特殊字符或格式问题'))
                } else {
                  callback(new Error('值集JSON格式错误'))
                }
              }
            }
          } else {
            callback()
          }
        }
    }
  ]
}

// 控件类型选项
const controlTypes = [
  { label: '文本控件', value: 'text' },
  { label: '数值控件', value: 'number' },
  { label: '枚举控件', value: 'enum' },
  { label: '日期控件', value: 'date' },
  { label: '复选框', value: 'checkbox' },
  { label: '单选框', value: 'radio' }
]

// 日期格式选项
const dateFormats = [
  { label: 'yyyy-MM-dd', value: 'yyyy-MM-dd' },
  { label: 'yyyy-MM-dd hh:mm:ss', value: 'yyyy-MM-dd hh:mm:ss' },
  { label: 'yyyy/MM/dd', value: 'yyyy/MM/dd' },
  { label: 'MM/dd/yyyy', value: 'MM/dd/yyyy' },
  { label: 'dd/MM/yyyy', value: 'dd/MM/yyyy' }
]

// 处理值集JSON
const handleValueSetChange = () => {
  try {
    if (valueSetJson.value.trim()) {
      // 清理可能的控制字符
      let cleanJson = valueSetJson.value
        .replace(/[\u0000-\u001F\u007F-\u009F]/g, '') // 移除控制字符
        .trim()
      
      const parsed = JSON.parse(cleanJson)
      if (Array.isArray(parsed)) {
        if (['enum', 'checkbox', 'radio'].includes(formData.value.type)) {
          (formData.value as any).valueSet = parsed
        }
      }
    }
  } catch (error) {
    console.warn('值集JSON格式错误:', error)
    // 可以添加用户友好的错误提示
    if (error instanceof SyntaxError) {
      console.warn('建议检查JSON格式，确保没有特殊字符或换行符')
    }
  }
}

// 生成值集JSON示例
const generateValueSetExample = () => {
  return `[{"value":"有","code":"98175"},{"value":"无","code":"98176"}]`
}

// 切换控件类型
const handleTypeChange = (type: string) => {
  formData.value.type = type as any
  
  // 根据类型设置默认值
  switch (type) {
    case 'date':
      (formData.value as any).dateFormat = 'yyyy-MM-dd hh:mm:ss'
      break
    case 'enum':
    case 'checkbox':
    case 'radio':
      if (!(formData.value as any).valueSet) {
        (formData.value as any).valueSet = []
        valueSetJson.value = ''
      }
      break
  }
}

// 确认处理
const handleConfirm = async () => {
  try {
    await formRef.value.validate()
    
    // 处理值集
    if (['enum', 'checkbox', 'radio'].includes(formData.value.type)) {
      handleValueSetChange()
    }
    
    emit('confirm', formData.value)
    dialogVisible.value = false
  } catch (error) {
    // 验证失败，不关闭对话框
  }
}

// 取消处理
const handleCancel = () => {
  emit('cancel')
  dialogVisible.value = false
  resetFormData()
}

// 重置表单数据
const resetFormData = () => {
  formData.value = {
    type: 'text',
    placeholder: '',
    defaultValue: ''
  }
  valueSetJson.value = ''
}

// 当对话框打开时重置数据
const handleOpen = () => {
  resetFormData()
  
  // 如果有初始数据，设置到表单
  if (props.initialData) {
    formData.value = { ...props.initialData }
    
    // 设置值集JSON
    if ((formData.value as any).valueSet && (formData.value as any).valueSet.length > 0) {
      valueSetJson.value = JSON.stringify((formData.value as any).valueSet, null, 2)
    }
  }
}
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    :width="width"
    :close-on-click-modal="false"
    :close-on-press-escape="true"
    @open="handleOpen">
    
    <!-- 根据类型显示对应的表单 -->
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="100px">
      
      <!-- 文本控件 -->
      <template v-if="formData.type === 'text'">
        <el-form-item label="占位符" prop="placeholder" required>
          <el-input
            v-model="formData.placeholder"
            placeholder="请输入占位符"
            clearable />
        </el-form-item>
        
        <el-form-item label="默认值" prop="defaultValue">
          <el-input
            v-model="formData.defaultValue"
            placeholder="请输入默认值"
            clearable />
        </el-form-item>
      </template>
      
      <!-- 数值控件 -->
      <template v-if="formData.type === 'number'">
        <el-form-item label="占位符" prop="placeholder" required>
          <el-input
            v-model="formData.placeholder"
            placeholder="请输入占位符"
            clearable />
        </el-form-item>
        
        <el-form-item label="默认值" prop="defaultValue">
          <el-input
            v-model="formData.defaultValue"
            placeholder="请输入默认值"
            clearable />
        </el-form-item>
      </template>
      
      <!-- 枚举控件 -->
      <template v-if="formData.type === 'enum'">
        <el-form-item label="占位符" prop="placeholder" required>
          <el-input
            v-model="formData.placeholder"
            placeholder="请输入占位符"
            clearable />
        </el-form-item>
        
        <el-form-item label="默认值" prop="defaultValue">
          <el-input
            v-model="formData.defaultValue"
            placeholder="请输入默认值"
            clearable />
        </el-form-item>
        
        <el-form-item label="值集" prop="valueSet" required>
          <el-input
            v-model="valueSetJson"
            type="textarea"
            :rows="6"
            placeholder="请输入值集JSON, 例:"
            @input="handleValueSetChange" />
          <div class="form-tip">
            示例: {{ generateValueSetExample() }}
          </div>
        </el-form-item>
      </template>
      
      <!-- 日期控件 -->
      <template v-if="formData.type === 'date'">
        <el-form-item label="占位符" prop="placeholder" required>
          <el-input
            v-model="formData.placeholder"
            placeholder="请输入占位符"
            clearable />
        </el-form-item>
        
        <el-form-item label="默认值" prop="defaultValue">
          <el-input
            v-model="formData.defaultValue"
            placeholder="请输入默认值"
            clearable />
        </el-form-item>
        
        <el-form-item label="日期格式" prop="dateFormat" required>
          <el-select
            v-model="(formData as any).dateFormat"
            placeholder="选择日期格式"
            style="width: 100%">
            <el-option
              v-for="format in dateFormats"
              :key="format.value"
              :label="format.label"
              :value="format.value" />
          </el-select>
        </el-form-item>
      </template>
      
      <!-- 复选框 -->
      <template v-if="formData.type === 'checkbox'">
        <el-form-item label="默认值" prop="defaultValue">
          <el-input
            v-model="formData.defaultValue"
            placeholder="请输入默认值"
            clearable />
        </el-form-item>
        
        <el-form-item label="值集" prop="valueSet" required>
          <el-input
            v-model="valueSetJson"
            type="textarea"
            :rows="6"
            placeholder="请输入值集JSON, 例:"
            @input="handleValueSetChange" />
          <div class="form-tip">
            示例: {{ generateValueSetExample() }}
          </div>
        </el-form-item>
      </template>
      
      <!-- 单选框 -->
      <template v-if="formData.type === 'radio'">
        <el-form-item label="默认值" prop="defaultValue">
          <el-input
            v-model="formData.defaultValue"
            placeholder="请输入默认值"
            clearable />
        </el-form-item>
        
        <el-form-item label="值集" prop="valueSet" required>
          <el-input
            v-model="valueSetJson"
            type="textarea"
            :rows="6"
            placeholder="请输入值集JSON, 例:"
            @input="handleValueSetChange" />
          <div class="form-tip">
            示例: {{ generateValueSetExample() }}
          </div>
        </el-form-item>
      </template>
    </el-form>
    
    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleConfirm">确定</el-button>
    </template>
  </el-dialog>
</template>

<style scoped>
.el-form-item {
  margin-bottom: 20px;
}

.el-form-item__label::before {
  content: '*';
  color: #f56c6c;
  margin-right: 4px;
}

/* 移除某些字段的必填标记 */
.el-form-item:nth-child(2) .el-form-item__label::before {
  content: '';
}

.form-tip {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
  line-height: 1.4;
}


</style> 